from firebase_admin import messaging
from Celery.celery import celery_app
from Model.models import Recommendation, User, db, ScenicSpot, Tag
from Service.TravelService import TravelPlanner
from Utils.RedisTokenPool import RedisTokenPool
import logging

from app import create_app

# Set up logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)


@celery_app.task(name="generate_travel_suggestion")
def generate_travel_suggestions(user_data, user_id):
    token = None
    app = create_app()
    tokens_key = "token_pool"
    tokens = app.config['TOKEN_POOL']
    token_pool = RedisTokenPool(tokens_key, tokens)

    try:
        # 获取令牌
        token = token_pool.get_token()
        travel_planner = TravelPlanner(token, app.config['AMAP_KEY_ROUTE'])
        guide, plan = travel_planner.generate_travel_suggestions(user_data)
        logger.info(f"Generated travel suggestions: {guide}, {plan}")
    except TimeoutError as te:
        logger.error(f"TimeoutError during getting token: {te}")
        return
    except Exception as e:
        logger.error(f"Error during travel suggestion generation: {e}")
        return
    finally:
        # 确保无论如何都释放令牌
        if token:
            token_pool.release_token(token)
    try:
        # 更新位置详情
        for day, day_data in plan.items():
            for time_range, details in day_data.items():
                location_name = details.get('行程地点', '')
                if location_name:
                    location_details = travel_planner.get_location_details(location_name, user_data["目的地"])
                    if location_details:
                        details.update(location_details)

        recommendation_data = {'guide': guide, 'plan': plan}
        recommendation = Recommendation(
            user_id=user_id,
            destination=user_data["目的地"],
            recommendation_data=recommendation_data
        )
        # 保存推荐到数据库
        with app.app_context():
            db.session.add(recommendation)
            db.session.commit()
            logger.info("Recommendation saved to the database")

        # 发送 FCM 通知
        send_fcm_notification(user_id, "Travel Recommendations Generated",
                              "Your travel recommendations are ready! Check them out now.")
    except Exception as e:
        db.session.rollback()
        logger.error(f"Error in recommendation processing: {e}")
        return


def send_fcm_notification(user_id, title, body):
    """发送 FCM 通知"""
    try:
        user = User.query.get(user_id)
        if user and user.fcm_token:
            message = messaging.Message(
                notification=messaging.Notification(title=title, body=body),
                token=user.fcm_token
            )
            response = messaging.send(message)
            logger.info(f"FCM notification sent successfully: {response}")
        else:
            logger.error(f"User with ID {user_id} not found or no FCM token available")
    except Exception as e:
        logger.error(f"Error sending FCM notification: {e}")


@celery_app.task
def batch_upload_task(file_urls, texts):
    app = create_app()  # Create an instance of your Flask app
    with app.app_context():  # Push an application context
        for url, text in zip(file_urls, texts):
            image_text_detail = ScenicSpot(image_url=url, text=text)
            db.session.add(image_text_detail)
            db.session.commit()


@celery_app.task
def batch_create_tags_task(tag_names):
    app = create_app()  # Create an instance of your Flask app
    with app.app_context():  # Push an application context
        new_tags = []
        for name in tag_names:
            if not Tag.query.filter_by(name=name).first():
                new_tag = Tag(name=name)
                db.session.add(new_tag)
                new_tags.append(new_tag)
                db.session.commit()
